package boun.swe.bob.dao;


import boun.swe.bob.entities.Bob_Event;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.*;


/**
 * Created by IntelliJ IDEA.
 * User: ememory
 * Date: 27.Ara.2010
 * Time: 16:21:04
 * To change this template use File | Settings | File Templates.
 */

@Component
public class Bob_EventDao extends GenericDaoImpl<Bob_Event, Integer> {

    private static final Logger LOG = Logger.getLogger(GroupDao.class);

    /**
     * returns event by primary key
     * @param eventId
     * @return
     */
    public Bob_Event findEventByEventId(final Integer eventId) {
        return (Bob_Event) hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery("select * from events e where e.event_id= ?").addEntity("e", Bob_Event.class);
                query.setInteger(0, eventId);
                return query.uniqueResult();
            }
        });
    }

    /**
     * returns events of users by userId
     * @param UserId
     * @return
     */
    public List<Bob_Event> findUserEventsByUserId(final Integer UserId) {
        return (List<Bob_Event>) hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery("select e.* from events e inner join event_member em on e.event_id = em.event_id where em.user_id = ? order by e.event_id desc").addEntity("e", Bob_Event.class);
                query.setInteger(0, UserId);
                return query.list();
            }
        });
    }

    /**
     * method for a user to join to an event
     * @param eventId
     * @param userId
     */
    public void JoinEvent(final int eventId, final int userId) {
        hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {

                if(!IsUserEvent(eventId,userId))
                {
                    Query query = session.createSQLQuery("insert into event_member(event_id,user_id,create_date) values(?,?,?)");
                    query.setInteger(0, eventId);
                    query.setInteger(1, userId);
                    query.setDate(2,new Date());
                    query.executeUpdate();
                }
                    return null;
            }
        });
    }

    /**
     * method for leaving an event
     * @param eventId
     * @param userId
     */
    public void LeaveEvent(final int eventId, final int userId) {
        hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                if(IsUserEvent(eventId,userId))
                {
                    Query query = session.createSQLQuery("delete from event_member where event_id=? and user_id=?");
                    query.setInteger(0, eventId);
                    query.setInteger(1, userId);
                    query.executeUpdate();
                }
                return null;
            }
        });
    }

    /**
     * determines whether the event belongs to user
     * @param eventId
     * @param userId
     * @return
     */
    public Boolean IsUserEvent(final int eventId,final int userId)
    {
        return (Boolean) hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery("select e.* from events e inner join event_member em on e.event_id=em.event_id where em.event_id= ? and em.user_id=?").addEntity("e", Bob_Event.class);
                query.setInteger(0, eventId);
                query.setInteger(1,userId);
                if(query.uniqueResult() != null)
                {
                    return true;
                }
                else
                {
                     return false;
                }
            }
        });
    }

    /**
     * returns event according to search keyword
     * @param keyword
     * @return
     */
    public List<Bob_Event> findEventsForSearch(final String keyword) {
        return (List<Bob_Event>) hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Set<Bob_Event> searchset = new HashSet<Bob_Event>();

                Query query = session.createSQLQuery("select * from events u where u.event_name like '%" + keyword + "%' ").addEntity("u", Bob_Event.class);
                List<Bob_Event> namelist = query.list();
                searchset.addAll(namelist);

                query = session.createSQLQuery("select * from events u where u.description like '%" + keyword + "%' ").addEntity("u", Bob_Event.class);
                List<Bob_Event> descriptionList = query.list();
                searchset.addAll(descriptionList);

                query = session.createSQLQuery("select * from events u where u.location like '%" + keyword + "%' ").addEntity("u", Bob_Event.class);
                List<Bob_Event> locationList = query.list();
                searchset.addAll(locationList);

                return new ArrayList<Bob_Event>(searchset);
            }
        });
    }

    /**
     * returns last inserted event
     * @param userId
     * @return
     */
     public Bob_Event findLastInsertedEvent(final int userId) {
        return (Bob_Event) hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery("select max(event_id) from events where owner_user_id = ?");
                query.setInteger(0, userId);
                Integer id = (Integer) query.uniqueResult();
                query = session.createSQLQuery("select * from events where event_id = ?").addEntity(Bob_Event.class);
                query.setInteger(0, id);
                return query.uniqueResult();
            }
        });
    }


}
